#!/usr/bin/env python
# coding: utf-8
# author: Wesley

from django.core.cache import cache
from django.conf import settings
from django.db import models

from lib.common import BasicManager


class DeviceManage(BasicManager):
    def update_user_device(self, devicetoken, userid, ostype, description, pad_token=None):
        device = self.get_user_device(userid)
        if device.get("devicetoken") != devicetoken or device.get("pad_token") != pad_token:
            self.update_or_create(
                devicetoken=devicetoken,
                defaults={
                    "user_id": userid,
                    "ostype": ostype,
                    "description": description,
                    "pad_token": pad_token,
                }
            )
            cache.delete(self.device_key.format(uid=userid))

    def get_user_device(self, userid):
        cache_key = self.device_key.format(uid=userid)
        device = cache.get(cache_key)

        if not device:
            device_values = ["devicetoken", "pad_token", "ostype"]
            device = self.filter(user__id=userid).order_by("-updated").values(*device_values).first()
            if device:
                cache.set(cache_key, device)
            else:
                device = {}

        return device


class Device(models.Model):
    """
    用户设备表, 将来消息推送要用到
    """
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="device")
    devicetoken = models.CharField(max_length=100, unique=True, db_index=True)  # 设备标识, 手机和pad都用这个字段
    pad_token = models.CharField(max_length=100, null=True, blank=True)  # 暂时无用
    updated = models.DateTimeField(auto_now=True)
    ostype = models.CharField(max_length=1, choices=settings.MOBILE_OS_CHOICES, default="0")  # 操作系统标识
    description = models.CharField(max_length=200, blank=True, null=True)  # 前端传的简要描述

    objects = DeviceManage()

    class Meta:
        db_table = "momself_device"


devicemanage = Device.objects
